﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace AsteroidWar
{
    public abstract class Hostile
    {
        public Sprite sprite;     
        protected Queue<Vector2> wayPoints = new Queue<Vector2>();       
        public bool Destroyed = false;

        protected float speed;

        protected Vector2 currentWayPoints = Vector2.Zero;
        protected Vector2 previousLocation = Vector2.Zero;

        public Hostile(
            Texture2D texture,
            Rectangle initialFrame,
            Vector2 location,
            int frameCounts,
            int radius,
            float speed)
        {
            sprite = new Sprite(location, texture, initialFrame, Vector2.Zero);
            sprite.CollisionRadius = radius;
            this.speed = speed;

            for (int i = 1; i < frameCounts; i++)
            {
                sprite.AddFrame(
                    new Rectangle(
                        initialFrame.X + (initialFrame.Width * i),
                        initialFrame.Y,
                        initialFrame.Width,
                        initialFrame.Height));
            }
            previousLocation = location;
            currentWayPoints = location;          
        }

        public void AddWayPoints(Vector2 wayPoint)
        {
            wayPoints.Enqueue(wayPoint);
        }

        public bool WayPointReach()
        {
            if (Vector2.Distance(sprite.Location, currentWayPoints) < sprite.Source.Width / 4)
                return true;
            else
                return false;
        }

        public abstract bool IsActive();

        public virtual void Update(GameTime gameTime)
        {
            if (IsActive())
            {
                Vector2 heading = currentWayPoints - sprite.Location;
                if (!heading.Equals(Vector2.Zero))
                {
                    heading.Normalize();
                }
                sprite.Velocity = heading * speed;
                previousLocation = sprite.Location;
                sprite.Update(gameTime);
                sprite.Rotation = (float)Math.Atan2(
                    sprite.Location.Y - previousLocation.Y,
                    sprite.Location.X - previousLocation.X
                    );

                if (WayPointReach())
                {
                    if (wayPoints.Count > 0)
                    {
                        currentWayPoints = wayPoints.Dequeue();
                    }
                }
            }
        }

        public abstract void Draw(SpriteBatch spriteBatch);
        
    }
}
